<template>
  <div class="view-fill">
    <div v-if="!detailModifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="'委外申请单详情'"
        :btn-list="fullInfo.btnList"
        :needReturn="!$route.query.processInstanceId"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button
            v-if="
              basicInfo.info.data.status === 7 &&
              proxy.$permission('outsourcingApplication:complete')
            "
            @click="generateInvoice"
            >维修完成</el-button
          >
          <el-button
            v-if="
              basicInfo.info.data.status === 7 &&
              proxy.$permission('outsourcingApplication:cancel')
            "
            @click="cancelOutsourcing"
            >取消维修</el-button
          >
          <el-button v-if="canRecall" @click="recall">撤回</el-button>
          <el-button v-if="canApprove" @click="btnFlow('approve')"
            >批准</el-button
          >
          <el-button v-if="canReject" @click="btnFlow('reject')"
            >驳回</el-button
          >
          <el-button v-if="canRefuse" @click="btnFlow('refuse')"
            >拒绝</el-button
          >
          <el-button v-if="canSalesReview" @click="salesReview">销审</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <basic-information
              :info="basicInfo.info"
              :label-width="basicInfo.labelWidth"
            >
            </basic-information>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 维修完成 -->
    <PageDialog
      v-show="outsourcingApplicationInfo.visible"
      :title="outsourcingApplicationInfo.title"
      v-model:visible="outsourcingApplicationInfo.visible"
      :width="outsourcingApplicationInfo.width"
      :bt-loading="outsourcingApplicationInfo.btLoading"
      :bt-list="outsourcingApplicationInfo.btList"
    >
      <PageForm
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="outsourcingApplicationInfo.formInfo.ref"
        :data="outsourcingApplicationInfo.formInfo.data"
        :field-list="outsourcingApplicationInfo.formInfo.fieldList"
        :rules="outsourcingApplicationInfo.formInfo.rules"
        :label-width="outsourcingApplicationInfo.formInfo.labelWidth"
      >
        <template v-slot:form-completeTime="scope">
          <el-date-picker
            v-model="outsourcingApplicationInfo.formInfo.data.completeTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择日期"
          />
        </template>
      </PageForm>
    </PageDialog>
    <outsourcing-application-modify
      v-if="detailModifyInfo.visible"
      v-model:visible="detailModifyInfo.visible"
      :table-row="detailModifyInfo.tableRow"
      :id="detailModifyInfo.tableRow.id"
      :title="detailModifyInfo.title"
      @returnBack="returnModify"
    />
  </div>
</template>

<script setup name="adjustPriceDetail">
import {
  detailOutsourcingApplication,
  submitOutsourcingApplication,
  approvedOutsourcingApplications,
  rejectOutsourcingApplications,
  refuseOutsourcingApplications,
  revokeOutsourcingApplication,
  salesOutsourcingApplication,
  completeOutsourcingApplication,
  cancelOutsourcingApplication,
} from '@/api/repair'
import moment from 'moment'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderOpAffairAll } from '@/api/affair'
const outsourcingApplicationModify = defineAsyncComponent(() =>
  import('./modify')
)
const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'tableRow', 'id'])

const basicInfo = reactive({
  info: {
    data: {},
    fieldList: [
      {
        label: '报修单据号',
        value: 'repairOrderNo',
        type: 'text',
      },
      {
        label: '委外申请单号',
        value: 'orderNo',
        type: 'text',
      },
      {
        label: '状态',
        value: 'statusValue',
        type: 'text',
      },
      {
        label: '报修类型',
        value: 'repairTypeName',
        type: 'text',
      },
      {
        label: '资产卡片号',
        value: 'assetCode',
        type: 'text',
      },
      {
        label: '资产名称',
        value: 'assetName',
        type: 'text',
      },
      {
        label: '资产位置',
        value: 'location',
        type: 'text',
      },
      {
        label: '使用部门',
        value: 'useDeptName',
        type: 'text',
      },
      {
        label: '故障时间',
        value: 'faultTime',
        type: 'text',
      },
      {
        label: '故障部位',
        value: 'faultPart',
        type: 'text',
      },
      {
        label: '故障描述',
        value: 'faultDescribe',
        type: 'text',
      },
      {
        label: '要求完成时间',
        value: 'requireCompleteTime',
        type: 'text',
      },
      {
        label: '预估费用',
        value: 'estimatedCost',
        type: 'text',
      },
      {
        label: '委托维修机构',
        value: 'entrustOrgName',
        type: 'text',
      },
      {
        label: '委托联系人',
        value: 'contactUser',
        type: 'text',
      },
      {
        label: '委托联系电话',
        value: 'contactPhone',
        type: 'text',
      },
      {
        label: '备注',
        value: 'remark',
        type: 'text',
      },
    ],
  },
  labelWidth: '130px',
})
const fullInfo = reactive({
  btnList: [{ value: 'button', type: 'slot' }],
})
const detailModifyInfo = reactive({
  visible: false,
  title: '',
  tableRow: {},
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 112,
    orderId: props.id || props.tableRow.id,
    sort: 'operate_time desc',
  },
})
const outsourcingApplicationInfo = reactive({
  visible: false,
  title: '委外维修完成登记',
  btLoading: false,
  type: '',
  row: {},
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseBtnGenerate, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveBtnGenerate,
      show: true,
    },
  ],
  formInfo: {
    ref: null,
    data: {
      completeTime: moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss'),
    },
    fieldList: [
      { label: '维修完成时间', value: 'completeTime', type: 'slot' },
      {
        label: '维修实际费用',
        value: 'actualCost',
        type: 'number',
        precision:
          proxy.$store.state.permission.systemConfig.assets_price_precision,
      },
    ],
    rules: {
      completeTime: [
        { required: true, message: '请选择维修完成时间', trigger: 'change' },
      ],
    },
    labelWidth: '120px',
  },
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('outsourcingApplication:submit') &&
    (basicInfo.info.data.status === 1 || basicInfo.info.data.status === 4)
  )
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('outsourcingApplication:modify') &&
    (basicInfo.info.data.status === 1 || basicInfo.info.data.status === 4)
  )
})
const canApprove = computed(() => {
  return (
    proxy.$permission('outsourcingApplication:approve') &&
    proxy.$store.state.permission.systemConfig
      .allow_entrust_maintenance_apply_approval == 1 &&
    basicInfo.info.data.status === 2
  )
})
const canReject = computed(() => {
  return (
    proxy.$permission('outsourcingApplication:reject') &&
    proxy.$store.state.permission.systemConfig
      .allow_entrust_maintenance_apply_approval == 1 &&
    basicInfo.info.data.status === 2
  )
})
const canRefuse = computed(() => {
  return (
    proxy.$permission('outsourcingApplication:refuse') &&
    proxy.$store.state.permission.systemConfig
      .allow_entrust_maintenance_apply_approval == 1 &&
    basicInfo.info.data.status === 2
  )
})
// 撤回
const canRecall = computed(() => {
  return (
    proxy.$permission('outsourcingApplication:recall') &&
    (basicInfo.info.data.status === 2 ||
      (basicInfo.info.data.status === 7 &&
        proxy.$store.state.permission.systemConfig
          .allow_entrust_maintenance_apply_approval == 0))
  )
})
// 销审
const canSalesReview = computed(() => {
  return (
    proxy.$permission('outsourcingApplication:salesReview') &&
    proxy.$store.state.permission.systemConfig
      .allow_entrust_maintenance_apply_approval != 0 &&
    basicInfo.info.data.status === 7
  )
})

onMounted(() => {
  getMain()
})

function returnBack() {
  emit('returnBack', false)
}
function update() {
  detailModifyInfo.title = '修改调价单'
  detailModifyInfo.tableRow = { ...basicInfo.info.data }
  detailModifyInfo.visible = true
}
//提交
function submit() {
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'outsourcingApplication',
    orderIds: [props.id || props.tableRow.id],
  }
  submitOutsourcingApplication(data).then((resp) => {
    if (resp && resp.success) {
      getMain()
    }
  })
}
// 按钮审批原因弹窗
function btnFlow(code) {
  const row = basicInfo.info.data
  const currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'approve') {
    currentBtnFlow.api = approvedOutsourcingApplications
    const data = {
      orderId: row.id,
    }
    currentBtnFlow.api(data).then((resp) => {
      if (resp && resp.success) {
        getMain()
      }
    })
    return
  } else if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectOutsourcingApplications
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseOutsourcingApplications
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          getMain()
        }
      })
    })
}
// 撤回
function recall() {
  revokeOutsourcingApplication([basicInfo.info.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      getMain()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 销审
function salesReview() {
  salesOutsourcingApplication([basicInfo.info.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      getMain()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
function cancelOutsourcing() {
  ElMessageBox.confirm('取消后将改变数据,是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      cancelOutsourcingApplication([basicInfo.info.data.id]).then((resp) => {
        if (resp && resp.success) {
          getMain()
        }
        handleCloseBtnGenerate()
      })
    })
    .catch((e) => {})
}
function generateInvoice() {
  outsourcingApplicationInfo.visible = true
}
function handleCloseBtnGenerate() {
  outsourcingApplicationInfo.visible = false
  outsourcingApplicationInfo.formInfo.data = {
    completeTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
  }
  proxy.$nextTick(() => {
    outsourcingApplicationInfo.formInfo.ref.clearValidate()
  })
}
function saveBtnGenerate() {
  outsourcingApplicationInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      completeOutsourcingApplication({
        ...basicInfo.info.data,
        ...outsourcingApplicationInfo.formInfo.data,
      }).then((resp) => {
        if (resp && resp.success) {
          getMain()
        }
        handleCloseBtnGenerate()
      })
    }
  })
}
function getMain() {
  detailOutsourcingApplication(props.id || props.tableRow.id).then((resp) => {
    if (resp && resp.success) {
      basicInfo.info.data = resp.data
    }
  })
}
function returnModify() {
  getMain()
}
</script>

<style scoped></style>
